/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/ban-types */
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import {
  Input,
  Table,
  Button,
  TableColumnsType,
  Form,
  Select,
  Checkbox,
  Col,
  Row,
  Spin,
  Modal,
} from "antd";
import "../css/store.scss";
import VehicleForm from "../VehicleModel/Form";
import type { UploadFile, UploadProps } from "antd";
import _ from "lodash";
import { DataType } from "./interfaceType";
import {
  uploadImage,
  updateVehicleType,
  addVehicleType,
  deleteVehicleType,
  getVehicleType,
} from "../../../api/index";
const seatOptions = ["0~2座", "3座", "4座", "5座", "6座以上"]; // 数据(座位数)
const bodyOptions = ["两厢", "三厢", "SUV", "商务车", "客车", "跑车", "旅行车"]; // 厢式
const displacementOptions = [
  "1.0及以上",
  "1.1-1.6L",
  "1.7-2.0L",
  "2.1-2.5L",
  "2.6-3.0L",
  "3.1-4.0L",
  "4.0L以上",
]; // 排量
export default function VehicleModel() {
  const columns: TableColumnsType<DataType> = [
    {
      title: "编号",
      width: 100,
      dataIndex: "cid",
      key: "key",
      defaultSortOrder: "ascend", //默认升序
      sorter: (a, b) => a.cid - b.cid,
    },
    {
      title: "车型/照片",
      width: 200,
      dataIndex: "cximage",
      key: "id",
      render: (imageUrl, record) => {
        const description = record.cxname;
        const imageUrlwithslash = imageUrl.replace(/\/upload/, "/upload/");
        return (
          <div style={{ display: "flex", alignItems: "center" }}>
            <img
              src={imageUrlwithslash}
              alt="车型照片"
              style={{
                maxWidth: "90px",
                maxHeight: "100px",
                borderRadius: "5px",
                marginLeft: "10px",
                marginRight: "10px",
              }}
            />
            <p className="text">{description}</p>
          </div>
        );
      },
    },
    {
      title: "品牌",
      width: 90,
      dataIndex: "brand",
      key: "brand",
    },
    {
      title: "款式",
      dataIndex: "style",
      key: "style",
      width: 90,
    },
    {
      title: "年款",
      dataIndex: "year",
      key: "year",
      width: 90,
    },
    {
      title: "座位数",
      dataIndex: "seats",
      key: "seats",
      width: 90,
    },
    {
      title: "厢式",
      dataIndex: "boxtype",
      key: "boxtype",
      width: 90,
    },
    {
      title: "排量",
      dataIndex: "displacement",
      key: "displacement",
      width: 90,
    },
    {
      title: "变速器类型",
      dataIndex: "TransmissionType",
      key: "TransmissionType",
      width: 100,
    },
    {
      title: "操作",
      key: "operation",
      fixed: "right",
      width: 180,
      render: (_, record) => {
        return (
          <div className="xiu">
            <Button
              type="primary"
              style={{ marginBottom: "5px", marginRight: "10px" }}
              onClick={() => showEditModal(record, record.cid)}
            >
              修改信息
            </Button>
            <Button
              style={{ marginBottom: "5px" }}
              onClick={() => Delete(record.cid)}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  const [selectedRecord, setSelectedRecord] = useState<DataType | undefined>(
    undefined
  ); // 表单数据
  const [selectedYears, setSelectedYears] = useState<string[]>([]); // 年款
  const [ids, setId] = useState(""); // 当前id
  const [open, setOpen] = useState(false); // 弹出层状态
  const [previewOpen, setPreviewOpen] = useState(false); // 上传图片(image)
  const [previewImage, setPreviewImage] = useState(""); // 上传图片(image)
  const [fileList, setFileList] = useState<UploadFile[]>([]); // 上传图片(image)
  const [editMode, setEditMode] = useState(false); // 判断是修改还是添加
  const [delVisible, setDelVisible] = useState(false); // 弹出层(删除)
  const [list, setList] = useState([]); // 存放车型数据
  const [brand, setBrand] = useState<string>(""); // 搜索(品牌)
  const [seats, setSeats] = useState(""); // 搜索(座位数)
  const [boxtype, setBoxtype] = useState(""); // 搜索(厢式)
  const [displacement, setDisplacement] = useState(""); // 搜索(排量)
  const [TransmissionType, setTransmissionType] = useState(""); // 搜索(变速器类型)
  const [spinning, setSpinning] = useState(false); // 刷新页面缓冲一秒
  // 获取年款信息
  const handleYearChange = (selectedValues: string[]) => {
    setSelectedYears(selectedValues);
  };
  // 关闭弹出层(添加/修改)
  const hideDelModal = () => {
    setOpen(false);
  };
  // 添加
  const showAddModal = () => {
    setOpen(true);
    setEditMode(false);
    setSelectedRecord(undefined);
  };
  // 修改回填
  const showEditModal = (record: DataType, id: any) => {
    setId(id);
    setOpen(true);
    setEditMode(true);
    setSelectedRecord(record);
  };
  const handleCancel = () => setPreviewOpen(false);
  // 上传图片
  const handleChange: UploadProps["onChange"] = async ({
    fileList: newFileList,
  }: {
    fileList: UploadFile[];
  }) => {
    setFileList(newFileList);
    if (newFileList[0]?.status === "done") {
      const formData = new FormData();
      formData.append("image", newFileList[0].originFileObj as File);
      const response = await uploadImage(formData);
      const imageUrlFromServer = response.data.path;
      setPreviewImage(imageUrlFromServer);
    }
  };
  // 获取到添加的数据
  const onFinish = async (values: any) => {
    if (editMode) {
      await updateVehicleType(values, previewImage, ids);
    } else {
      await addVehicleType(values, previewImage);
    }
    setOpen(false);
    getlist();
  };
  // 开启弹出层(删除)
  const Delete = (id: any) => {
    setId(id);
    setDelVisible(true);
  };
  // 关闭弹出层(删除)
  const hideDelModal1 = () => {
    setDelVisible(false);
  };
  // 删除数据
  const delVehicle = async () => {
    await deleteVehicleType(ids);
    setDelVisible(false);
    getlist();
  };
  // 防抖搜索(品牌)
  const onChange = _.debounce((value: any) => {
    setBrand(value.target.value);
  }, 500);
  // 搜索(座位数)
  const onChange1 = (value: any) => {
    setSeats(value);
  };
  // 搜索(厢式)
  const onChange2 = (value: any) => {
    setBoxtype(value);
  };
  // 搜索(排量)
  const onChange3 = (value: any) => {
    setDisplacement(value);
  };
  // 搜索(变速器类型)
  const onChange4 = (value: any) => {
    setTransmissionType(value);
  };
  // 获取初始值+搜索
  const getlist = async () => {
    const { data } = await getVehicleType(
      brand,
      selectedYears,
      seats,
      boxtype,
      displacement,
      TransmissionType
    );
    const updatedList = data.data.map((item: { cid: any }) => ({
      ...item,
      key: item.cid,
    }));
    setList(updatedList);
  };
  useEffect(() => {
    getlist();
  }, [brand, selectedYears, seats, boxtype, displacement, TransmissionType]);
  useEffect(() => {
    setSpinning(true);
    setTimeout(() => {
      setSpinning(false);
    }, 1000);
  }, []);
  return (
    <div className="storeBigBox">
      <Spin spinning={spinning} tip="Loading...">
        <Header title="车型管理" />
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ marginTop: "5px", width: "300px", marginLeft: "15px" }}
        >
          <Form.Item name="brand" label="搜索品牌" style={{ width: "300px" }}>
            <Input placeholder="请输入内容" onChange={(e) => onChange(e)} />
          </Form.Item>
          <Form.Item
            name="year"
            label="年款"
            hasFeedback
            style={{ marginTop: "-15px", width: "300px" }}
          >
            <Select
              placeholder="选择年款"
              style={{ width: "100px" }}
              mode="multiple"
              onChange={handleYearChange}
              value={selectedYears}
            >
              <Select.Option value="2023">2023</Select.Option>
              <Select.Option value="2024">2024</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="seats" label="座位数" style={{ marginTop: "-15px" }}>
            <Checkbox.Group
              style={{ width: "500px" }}
              onChange={(value) => onChange1(value)}
            >
              <Row>
                {seatOptions.map((item, index) => (
                  <Col span={4} key={index}>
                    <Checkbox value={item} style={{ lineHeight: "32px" }}>
                      {item}
                    </Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </Form.Item>
          <Form.Item name="boxtype" label="厢式" style={{ marginTop: "-15px" }}>
            <Checkbox.Group
              style={{ width: "900px" }}
              onChange={(value) => onChange2(value)}
            >
              <Row>
                {bodyOptions.map((item, index) => (
                  <Col span={2} key={index}>
                    <Checkbox value={item} style={{ lineHeight: "32px" }}>
                      {item}
                    </Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </Form.Item>
          <Form.Item
            name="displacement"
            label="排量"
            style={{ marginTop: "-15px" }}
          >
            <Checkbox.Group
              style={{ width: "1200px" }}
              onChange={(value) => onChange3(value)}
            >
              <Row>
                {displacementOptions.map((item, index) => (
                  <Col span={2} key={index}>
                    <Checkbox value={item} style={{ lineHeight: "32px" }}>
                      {item}
                    </Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </Form.Item>
          <Form.Item
            name="TransmissionType"
            label="变速器类型"
            style={{ marginTop: "-15px" }}
          >
            <Checkbox.Group
              style={{ width: "1200px" }}
              onChange={(value) => onChange4(value)}
            >
              <Checkbox value="手动" style={{ lineHeight: "32px" }}>
                手动
              </Checkbox>
              <Checkbox value="自动" style={{ lineHeight: "32px" }}>
                自动
              </Checkbox>
            </Checkbox.Group>
          </Form.Item>
        </Form>
        <div className="storeContent">
          <Button
            type="primary"
            style={{ float: "right", marginBottom: "10px" }}
            onClick={showAddModal}
          >
            添加车辆
          </Button>
          <div className="num">总计:{list.length}</div>
          <Table columns={columns} dataSource={list}  pagination={{
              defaultPageSize: 1, //默认煤业显示条数
              defaultCurrent: 1, //默认当前页数第一页
              pageSizeOptions: ["3", "5", "10"], //每页显示多少条
              locale: {
                items_per_page: "条/页",
              },
            }}/>
        </div>
        <Modal
          title={editMode ? "编辑车型" : "添加车型"}
          visible={open}
          onCancel={hideDelModal}
          footer={[]}
          width="900px"
          bodyStyle={{
            maxHeight: "70vh",
            overflowY: "auto",
            overflowX: "hidden",
          }}
        >
          <VehicleForm
            previewOpen={previewOpen}
            editMode={editMode}
            previewImage={previewImage}
            handleCancel={handleCancel}
            fileList={fileList}
            handleChange={handleChange}
            onFinish={onFinish}
            selectedRecord={selectedRecord}
            setFileList={setFileList}
            setPreviewOpen={setPreviewOpen}
          />
        </Modal>
        {/* 删除 */}
        <Modal
          title="删除车辆"
          visible={delVisible}
          onCancel={hideDelModal1}
          footer={null}
          centered
          width="400px"
        >
          <div className="del-modal">
            <p className="del-message">确定要删除该车型吗？</p>
            <div className="del-modal-btn">
              <Button onClick={hideDelModal1} className="simple-btn cancel-btn">
                取消
              </Button>
              <Button
                type="primary"
                onClick={delVehicle}
                className="simple-btn confirm-btn"
              >
                确定
              </Button>
            </div>
          </div>
        </Modal>
      </Spin>
    </div>
  );
}
